import os
import re
from bs4 import BeautifulSoup
import requests
import json
import traceback
import logging  # 用于日志控制
import time
from time import strftime, localtime

# 日志基础配置
# 创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 创建一个handler，用于写入日志文件
# w 模式会记住上次日志记录的位置
fh = logging.FileHandler('./log.txt', mode='a', encoding='utf-8')
fh.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(fh)
# 创建一个handler，输出到控制台
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter("[%(asctime)s]:%(levelname)s:%(message)s"))
logger.addHandler(ch)


# 返回要推送的通知内容
# 对html的适配要更好
# 增加文件关闭操作
def readFile_html(filepath):
    content = ''
    with open(filepath, "r", encoding='utf-8') as f:
        for line in f.readlines():
            content += line + '<br>'
    return content


def sendPushplus(token,man):
    try:
        # 发送内容
        data = {
            "token": token,
            "title": man+"人查询到最新核酸记录",
            "content": readFile_html('./log.txt')
        }
        url = 'http://www.pushplus.plus/send'
        headers = {'Content-Type': 'application/json'}
        body = json.dumps(data).encode(encoding='utf-8')
        resp = requests.post(url, data=body, headers=headers)
        logging.info("已完成推送~")
    except Exception as e:
        print('push+通知推送异常，原因为: ' + str(e))
        logger.info('push+通知推送异常，原因为: ' + str(e))
        print(traceback.format_exc())


# 以下内容无需改动
user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0"
host = "jksb.v.zzu.edu.cn"
origin = "https://jksb.v.zzu.edu.cn"
session = requests.session()
info = ["0", "1"]
result = []

data = {
    "ptopid": "",
    "sid": "",
}


# 登录函数
def login(account, password):
    header = {
        "Origin": origin,
        "Referer": "https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/first0",
        "User-Agent": user_agent,
        "Host": host,
    }
    post_url = "https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/login"
    post_data = {
        "uid": account,
        "upw": password,
        "smbtn": "进入健康状况上报平台",
        "hh28": "722",
    }
    response = session.post(post_url, data=post_data, headers=header)
    response.encoding = "utf-8"
    status = get_session_data(response.text)
    if status:
        logging.info(f'{account}登录成功')
        return 1
    else:
        logging.info(f'{account}登录失败，等待重试...')
        time.sleep(600)
        login(account, password)


# 获取登录的session信息
def get_session_data(html):
    r = re.search('ptopid=(.*)&sid=(.*)"', html)
    global info
    if r:
        info[0] = r.group(1)
        info[1] = r.group(2)
        return 1
    else:
        return 0


# 查询核酸结果
def submit():
    url = "https://jksb.v.zzu.edu.cn/vls6sss/zzujksb.dll/getzhbofmen"
    headers = {
        "User-Agent": user_agent,
        "Host": host,
        "Origin": origin,
    }
    params = {
        'ptopid': info[0],
        'sid': info[1]
    }
    r = requests.get(url, headers=headers, params=params)
    r.encoding = "utf-8"
    b = r.text
    soup = BeautifulSoup(b, "html.parser")
    c = str(soup.head.script)
    res = re.search('核酸结果时间<br />(.*)</div><div style=\'width:20px;height:100%', c)
    if res:
        d = str(res.group(1))
        return d
    else:
        time.sleep(300)
        submit()


def hsjg(number, id_card):
    login(number, id_card)
    res = submit()
    logging.info(f"{number}成功获取,结果是{res}")
    return res

try:
    token = os.environ["token"]
except:
    token = ""
    logging.info("请填写环境变量token,使用PushPlus推送\n")

def main_run():
    all_users = []
    try:
        cookie_list = os.environ["ZZU"].split('&')  # 获取cookie_list的合集
        if len(cookie_list) < 1:
            logging.info('请填写环境变量ZZU,格式：2019xxx,身份证号后8位\n')
        users = cookie_list[0].split(';')
        for user in users:
            temp = []
            temp.append(int(user.split(',')[0]))
            temp.append(user.split(',')[1])
            all_users.append(temp)
    except:
        all_users = []
        logging.info("未填写环境变量ZZU,格式:2019xxx,身份证后8位;2019xxx;身份证后8位")
    return all_users

all_users = main_run()
print(all_users)

# main方法
if __name__ == "__main__":
    open('./log.txt', mode='w', encoding='utf-8')
    s = 10  # 设置延迟时间（秒）
    man = 0
    for user in all_users:
        res = hsjg(user[0], user[1])
        now = strftime("%Y-%m-%d %H:%M:%S", localtime())

        t1 = (int(res[8]) * 10 + int(res[9])) * 24 + (int(res[11]) * 10 + int(res[12]))
        t2 = (int(now[8]) * 10 + int(now[9])) * 24 + (int(now[11]) * 10 + int(now[12]))

        if t2 - t1 < 8:
            man += 1
        time.sleep(s)
    if all_users:
        logging.info(f"已查询到{man}人最新核酸检测结果,{6 - man}人未查询到结果！")
    else:
        logging.info("未查询到环境变量ZZU,无法查询！")
    if token:
        sendPushplus(token,str(man))
    else:
        logging.info("未查询到环境变量token,无法推送！")
